//
//  XWXSqliteDataBasePool.m
//  XWXSqlite
//
//  Created by 许卫星 on 17/9/4.
//  Copyright © 2017年 wxxu. All rights reserved.
//  数据库管理池,用于管理多个数据库对象

#import "XWXSqliteDataBasePool.h"
#import "XWXSqliteDataBaseTool.h"

@interface XWXSqliteDataBasePool()
@property (nonatomic, strong) NSMutableDictionary *sqliteDataBasePool;
@property (nonatomic, strong) NSLock *poolLock;
@end

@implementation XWXSqliteDataBasePool


+ (XWXSqliteDataBasePool *)sharedInstance
{
    static XWXSqliteDataBasePool *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[XWXSqliteDataBasePool alloc] init];
    });
    return sharedInstance;
}

/**
 根据数据库名称获取一个数据库
 @param databaseName 数据库名称
 @return 数据库对象
 */
- (XWXSqliteDataBase *)databaseWithName:(NSString *)databaseName
{
    [self.poolLock lock];
    NSString *dbName = [XWXSqliteDataBaseTool getDBNameWithName:databaseName];
    XWXSqliteDataBase *sqliteDataBase = self.sqliteDataBasePool[dbName];
    if (sqliteDataBase == nil) {
        sqliteDataBase = [[XWXSqliteDataBase alloc] initWithDBWithDBName:dbName];
        self.sqliteDataBasePool[dbName] = sqliteDataBase;
    }
    if (![sqliteDataBase isOpen]) {
        [sqliteDataBase openDBWithDBName:databaseName];
    }
    [self.poolLock unlock];
    return sqliteDataBase;
}


/**
 根据数据库名称关闭一个数据库
 @param databaseName 数据库名称
 */
- (void)closeDataBaseWithName:(NSString *)databaseName
{
    NSString *dbName = [XWXSqliteDataBaseTool getDBNameWithName:databaseName];
    XWXSqliteDataBase *sqliteDataBase = self.sqliteDataBasePool[dbName];
    [sqliteDataBase closeDB];
    [self.sqliteDataBasePool removeObjectForKey:dbName];
}


/**
 关闭所有数据库
 */
- (void)closeAllDataBase
{
    [self.sqliteDataBasePool enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:XWXSqliteDataBase.class]) {
            XWXSqliteDataBase *sqliteDataBase = (XWXSqliteDataBase *)obj;
            [sqliteDataBase closeDB];
        }
    }];
}


- (NSMutableDictionary *)sqliteDataBasePool
{
    if (_sqliteDataBasePool == nil) {
        _sqliteDataBasePool = [[NSMutableDictionary alloc] init];
    }
    return _sqliteDataBasePool;
}

- (NSLock *)poolLock
{
    if (_poolLock == nil) {
        _poolLock = [[NSLock alloc] init];
    }
    return _poolLock;
}
@end
